package cn.tedu.charging.order.timer;

import cn.tedu.charging.common.pojo.po.ChargingBillExceptionPO;
import cn.tedu.charging.common.pojo.po.ChargingBillSuccessPO;
import cn.tedu.charging.order.config.XxlJobConfig;
import cn.tedu.charging.order.mapper.BillExceptionMapper;
import cn.tedu.charging.order.mapper.BillSuccessMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.context.XxlJobContext;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 专门负责检查订单是否结束
 * 定时任务也算是一个程序入口,应该调用业务层来完成定时的功能
 */
@Component
@Slf4j
public class OrderStatusCheckJob {
    @Autowired
    private BillSuccessMapper billSuccessMapper;
    @Autowired
    private BillExceptionMapper billExceptionMapper;
    //注解指定jobHandler需要固定 order-status-check
    @XxlJob("order-status-check")
    public void orderStatusCheck(){
        //1.获取定时任务的参数 订单编号
        String billId = XxlJobContext.getXxlJobContext().getJobParam();
        log.debug("订单定时任务,开始执行,检查订单状态是否结束,billId:{}",billId);
        //2.查询当前success成功订单
        ChargingBillSuccessPO success=getSuccessByBillId(billId);
        //判断 存在且状态为1
        if (success!=null&&success.getBillStatus()==1){
            log.error("订单异常,按照异常处理,billId:{}",billId);
            //3.存储生成一个异常数据
            saveExceptionBill(success);
            //4.修改订单状态为3 异常结束
            updateBillStatus(success,3);
            //TODO 5. 通知用户具体情况
        }else{
            log.debug("订单正常,定时任务结束,billId:{}",billId);
        }
    }

    private void updateBillStatus(ChargingBillSuccessPO success, Integer status) {
        //update charging_success_bill set bill_status=3 where id=?
        ChargingBillSuccessPO poParam=new ChargingBillSuccessPO();
        poParam.setId(success.getId());
        poParam.setBillStatus(status);
        billSuccessMapper.updateById(poParam);
    }

    private void saveExceptionBill(ChargingBillSuccessPO success) {
        //1.组织一个po
        ChargingBillExceptionPO exception=new ChargingBillExceptionPO();
        exception.setBillId(success.getBillId());
        exception.setCreateTime(new Date());
        exception.setDeleted(0);
        //2.新增到异常
        billExceptionMapper.insert(exception);
    }

    private ChargingBillSuccessPO getSuccessByBillId(String billId) {
        //select * from charging_bill_success where bill_id=?
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("bill_id",billId);
        return billSuccessMapper.selectOne(queryWrapper);
    }
}
